package common.action;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONObject;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import common.utils.FileUtil;

@Controller("uploadAction")
@Scope("prototype")
public class UploadAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private String UPLOADFILE = "uploadfile";

	private File filedata;
	private String filename;

	public void uploadimage() throws Exception {

		List<String> fileTypes = new ArrayList<String>();
		String type = "*.jpg;*.png;*.jpeg;*.bmp;*.gif;".trim();
		double size = 12;
		String[] types = type.split(";");
		for (int i = 0; i < types.length; i++) {
			fileTypes.add(types[i].replace("*.", ""));
		}
		response.getWriter().write(upload(fileTypes, size, null));
	}

	// maxSize单位是mb
	private String upload(List<String> fileTypes, double maxSize,
			String basepath) {

		String fileExt = filename.substring(filename.lastIndexOf(".") + 1)
				.toLowerCase();
		if (!fileTypes.contains(fileExt)) {
			return getError("上传文件扩展名[" + fileExt + "]是不允许的扩展名。");
		}
		if (filename.length() > maxSize * 1024 * 1024) {
			return getError("上传文太大");
		}
		// 创建文件夹
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String ymd = sdf.format(new Date());
		String savePath = UPLOADFILE + "/" + ymd + "/";
		String newfilename = FileUtil.randomRename(filename);

		File dirFile = new File(rootPath + savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		filedata.renameTo(new File(rootPath + savePath + newfilename));
		return "{'success':true,'url':'" + savePath + newfilename
				+ "','filename':'" + filename + "','newfilename':'"
				+ newfilename + "'}";
	}

	private String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toString();
	}

	public File getFiledata() {
		return filedata;
	}

	public void setFiledata(File filedata) {
		this.filedata = filedata;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

}